<template>
  <div class="w-100">
    <div class="container">
      <div class="chat-window">
        <div class="messages">
          <div v-for="(message, index) in messages" :key="index"
               :class="{'user': message.from === 'user', 'bot': message.from === 'bot'}">
            {{ message.text }}
          </div>
        </div>
        <input v-model="userInput" @keyup.enter="sendMessage" placeholder="Type your message here..."/>
        <button @click="sendMessage">Send</button>
      </div>
    </div>
  </div>
</template>

<script>

import {postJson} from "@/api/http";

export default {
  name: "AiPlan",
  data() {
    return {
      messages: [],
      userInput: '',
      apiUrl: 'YOUR_AI_API_URL_HERE', // 替换为你的 AI API URL
      apiKey: 'YOUR_API_KEY_HERE'     // 替换为你的 API 密钥
    };
  },
  methods: {
    async sendMessage() {
      if (this.userInput.trim() === '') return;

      const config = {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.apiKey}`
        }
      };

      const body = {
        query: this.userInput
      };

      try {
        const res = await postJson(this.apiUrl, body, config);
        const answer = res.data.answer; // 根据你的 API 响应格式调整

        this.messages.push({from: 'user', text: this.userInput});
        this.messages.push({from: 'bot', text: answer});
        this.userInput = '';
      } catch (error) {
        console.error('Error fetching AI response:', error);
        this.messages.push({from: 'bot', text: 'Sorry, I couldn\'t understand your message.'});
      }
    }
  }
};
</script>
<style scoped lang="less">

.chat-container {
  width: 300px;
  margin: 0 auto;
}

.chat-window {
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 5px;
}

.messages {
  max-height: 300px;
  overflow-y: auto;
  margin-bottom: 10px;
}

.message {
  margin: 5px 0;
  padding: 5px;
  border-radius: 5px;
}

.user {
  background-color: #e0f7fa;
}

.bot {
  background-color: #fff9c4;
}

input {
  width: calc(100% - 22px);
  padding: 10px;
  box-sizing: border-box;
}

button {
  padding: 10px;
  margin-top: 5px;
  cursor: pointer;
}
</style>
